const { resolve, extname } = require('path')
const fs = require('fs')
const fg = require('fast-glob')

module.exports = function (options = {}) {
    options = Object.assign(options, {
        content: 'src/**/*.{jsx,tsx,vue}'
    })
    let contentList = fg.sync([options.content], { unique: true, absolute: true });
    return {
        name: 'vite-tailwindcss-uni',
        enforce: 'pre',
        async transform(code, id) {
            if (!contentList.includes(id)) return
            code = fs.readFileSync(id, "utf8")
            let codes = code.split('class="')

            codes.forEach((code, i) => {
                if (i === 0) return
                let codeArr = code.split('"')
                if (!codeArr[0]) return
                let codeArr0 = codeArr[0].split("'");
                codeArr0.forEach((d, i) => {
                    console.log('start', d)
                    if (!d.startsWith(':') && !d.startsWith('[') && !d.includes('?') && !d.includes('|') && !d.includes('&') && !d.includes('=')) {
                        codeArr0[i] = d
                            .replace(/\!([A-Za-z0-9|\-]+)/g, `_$1`)
                    }
                    d = codeArr0[i]
                    codeArr0[i] = d.replace(/\-\[/g, `-_`)
                        .replace(/\#|\//g, `_`)
                        .replace(/\%\]/g, `__`)
                        .replace(/([0-9]+)(\.)/g, `$1_`)
                        .replace(/([A-Za-z0-9]+)(\:)([A-Za-z0-9]+)/g, `$1_$3`)
                        .replace(/([A-Za-z0-9]+)(\]|\%)/g, `$1_`)
                        .replace(/([A-Za-z0-9]+)\.([A-Za-z0-9]+)_/g, `$1.$2]`)
                })
                codeArr[0] = codeArr0.join("'")
                console.log('end', codeArr[0])
                codes[i] = codeArr.join('"')
            })
            code = codes.join('class="')

            return code
        }

    }
}